package com.guigu.health.realm;

import com.alibaba.dubbo.config.annotation.Reference;
import com.guigu.health.pojo.User;
import com.guigu.health.pojo.UserRolePermission;
import com.guigu.health.service.UserRolePermissionService;
import com.guigu.health.service.UserService;
import com.mysql.jdbc.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName:HealthRealm
 * @Description:
 * @Author:longtao
 * @Date:2021/3/29
 * @Version:1.0
 */
public class HealthRealm extends AuthorizingRealm {
    @Reference
    public UserService userService;

    @Reference
    private UserRolePermissionService userRolePermissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //方法一：获得user对象

       User user= (User) principalCollection.getPrimaryPrincipal();

        //获取list
        if (!StringUtils.isNullOrEmpty(user.getAccount())) {
            List<UserRolePermission> list = userRolePermissionService.queryAllByUserID(user.getAccount());
            List<String> stringList=new ArrayList<String>();
            if (list.size() != 0) {
                for (UserRolePermission permission : list) {
                    stringList.add(permission.getPermissionKeyWord());
                }
            }
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addStringPermissions(stringList);
            return info;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        /**
         * 获取用户名
         */
        String userName = (String) token.getPrincipal();
        /**
         * 获取user对象
         */
        User user = userService.loginUser(userName);
        //4.用户存在则进行密码校验，否则，抛出异常：系统管理员不存在;
        if (user != null) {
            /**
             * 当前realm对象的name
             */
            String realmName = this.getName();
            /**
             * 获取随机盐
             */
            String salt = userService.getSalt(userName);
            ByteSource source = ByteSource.Util.bytes(salt);
            /**
             * 参数分别为:
             * 1.数据库中的账号
             * 2.数据库中的密码
             * 3.随机盐
             * 4.当前realm对象的名字
             */
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), source, realmName);
            return authenticationInfo;
        } else {
            //没找到帐号
            throw new UnknownAccountException("不存在该用户");
        }
    }
}
